package api

import (
	"getaway/basic/config"
	__ "getaway/basic/proto/orderproto"
	"getaway/handler/request"
	"getaway/handler/response"
	"getaway/middleware"
	"github.com/gin-gonic/gin"
	"strconv"
)

// GetFinancialReconciliation
// @Summary      获取财务对账数据
// @Description  获取财务对账数据
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        financial   query    request.FinancialReconciliationReq    true  "财务对账参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/reconciliation [get]
// @Security TokenAuth
func GetFinancialReconciliation(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.FinancialReconciliationReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以查看所有数据
	if authorityId != 3 && req.UserId == "" {
		response.ParameterError(c, "权限不足", "非管理员用户必须指定用户ID")
		return
	}

	// 调用财务对账服务
	res, err := config.OrderClient.GetFinancialReconciliation(c, &__.FinancialReconciliationReq{
		StartDate:       req.StartDate,
		EndDate:         req.EndDate,
		OrderStatus:     req.OrderStatus,
		PaymentMethod:   req.PaymentMethod,
		Page:            req.Page,
		PageSize:        req.PageSize,
		TransactionType: req.TransactionType,
		UserId:          req.UserId,
		DriverId:        req.DriverId,
		MinAmount:       req.MinAmount,
		MaxAmount:       req.MaxAmount,
		OrderSn:         req.OrderSn,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询财务对账行为
	middleware.RecordClickBehavior(c, userId, "查询财务对账", map[string]interface{}{
		"startDate": req.StartDate,
		"endDate":   req.EndDate,
		"userId":    req.UserId,
		"page":      req.Page,
		"pageSize":  req.PageSize,
		"success":   err == nil,
	})

	response.Success(c, "查询财务对账成功", res)
}

// ExportFinancialReconciliation
// @Summary      导出财务对账数据
// @Description  导出财务对账数据
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        financial   body    request.ExportFinancialReconciliationReq    true  "导出财务对账参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/export [post]
// @Security TokenAuth
func ExportFinancialReconciliation(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.ExportFinancialReconciliationReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以导出数据
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以导出财务数据")
		return
	}

	// 调用导出财务对账服务
	res, err := config.OrderClient.ExportFinancialReconciliation(c, &__.ExportFinancialReconciliationReq{
		StartDate:       req.StartDate,
		EndDate:         req.EndDate,
		OrderStatus:     req.OrderStatus,
		PaymentMethod:   req.PaymentMethod,
		UserId:          req.UserId,
		TransactionType: req.TransactionType,
		FilterUserId:    req.FilterUserId,
		FilterDriverId:  req.FilterDriverId,
		MinAmount:       req.MinAmount,
		MaxAmount:       req.MaxAmount,
		OrderSn:         req.OrderSn,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录导出财务对账行为
	middleware.RecordClickBehavior(c, userId, "导出财务对账", map[string]interface{}{
		"startDate": req.StartDate,
		"endDate":   req.EndDate,
		"userId":    req.UserId,
		"success":   err == nil,
	})

	response.Success(c, "导出财务对账成功", res)
}

// CreateDispute
// @Summary      创建争议
// @Description  创建争议
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        dispute   body    request.CreateDisputeReq    true  "创建争议参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/dispute/create [post]
// @Security TokenAuth
func CreateDispute(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.CreateDisputeReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用创建争议服务
	res, err := config.OrderClient.CreateDispute(c, &__.CreateDisputeReq{
		BillingId:   req.BillingId,
		UserId:      req.UserId,
		DisputeType: req.DisputeType,
		Priorty:     req.Priority,
		DisputeDesc: req.Description,
		Evidence:    req.Evidence,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录创建争议行为
	middleware.RecordClickBehavior(c, userId, "创建争议", map[string]interface{}{
		"billingId":   req.BillingId,
		"userId":      req.UserId,
		"disputeType": req.DisputeType,
		"priority":    req.Priority,
		"success":     err == nil,
	})

	response.Success(c, "创建争议成功", res)
}

// ResolveDispute
// @Summary      解决争议
// @Description  解决争议
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        dispute   body    request.ResolveDisputeReq    true  "解决争议参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/dispute/resolve [post]
// @Security TokenAuth
func ResolveDispute(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.ResolveDisputeReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以解决争议
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以解决争议")
		return
	}

	// 调用解决争议服务
	res, err := config.OrderClient.ResolveDispute(c, &__.ResolveDisputeReq{
		DisputeId:  req.DisputeId,
		Resolution: req.Resolution,
		ResolvedBy: uint32(userId),
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录解决争议行为
	middleware.RecordClickBehavior(c, userId, "解决争议", map[string]interface{}{
		"disputeId":      req.DisputeId,
		"resolutionType": req.ResolutionType,
		"compensation":   req.Compensation,
		"success":        err == nil,
	})

	response.Success(c, "解决争议成功", res)
}

// GetDisputeRecords
// @Summary      获取争议记录
// @Description  获取争议记录
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        dispute   query    request.GetDisputeRecordsReq    true  "获取争议记录参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/dispute/records [get]
// @Security TokenAuth
func GetDisputeRecords(c *gin.Context) {
	userId := c.GetUint("userId")
	var req request.GetDisputeRecordsReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用获取争议记录服务
	res, err := config.OrderClient.GetDisputeRecords(c, &__.GetDisputeRecordsReq{
		Status:   req.Status,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询争议记录行为
	middleware.RecordClickBehavior(c, userId, "查询争议记录", map[string]interface{}{
		"page":     req.Page,
		"pageSize": req.PageSize,
		"status":   req.Status,
		"success":  err == nil,
	})

	response.Success(c, "查询争议记录成功", res)
}

// ComprehensiveValidation
// @Summary      综合验证
// @Description  综合验证财务系统
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        validation   body    request.ComprehensiveValidationReq    true  "综合验证参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/validation [post]
// @Security TokenAuth
func ComprehensiveValidation(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.ComprehensiveValidationReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以执行综合验证
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以执行综合验证")
		return
	}

	// 调用综合验证服务
	res, err := config.OrderClient.ComprehensiveValidation(c, &__.ComprehensiveValidationReq{
		StartDate:           req.StartDate,
		EndDate:             req.EndDate,
		ValidateIncome:      req.ValidateIncome,
		ValidateExpense:     req.ValidateExpense,
		ValidatePayment:     req.ValidatePayment,
		ValidateRefund:      req.ValidateRefund,
		ValidateReports:     req.ValidateReports,
		ValidateCalculation: req.ValidateCalculation,
		ValidateConsistency: req.ValidateConsistency,
		ValidateConcurrency: req.ValidateConcurrency,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录综合验证行为
	middleware.RecordClickBehavior(c, userId, "综合验证", map[string]interface{}{
		"startDate":           req.StartDate,
		"endDate":             req.EndDate,
		"validateIncome":      req.ValidateIncome,
		"validateExpense":     req.ValidateExpense,
		"validatePayment":     req.ValidatePayment,
		"validateRefund":      req.ValidateRefund,
		"validateReports":     req.ValidateReports,
		"validateCalculation": req.ValidateCalculation,
		"validateConsistency": req.ValidateConsistency,
		"validateConcurrency": req.ValidateConcurrency,
		"success":             err == nil,
	})

	response.Success(c, "综合验证完成", res)
}

// GetExceptionSummary
// @Summary      获取异常摘要
// @Description  获取异常摘要
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        summary   query    request.GetExceptionSummaryReq    true  "获取异常摘要参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/exception/summary [get]
// @Security TokenAuth
func GetExceptionSummary(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.GetExceptionSummaryReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以查看异常摘要
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以查看异常摘要")
		return
	}

	// 调用获取异常摘要服务
	res, err := config.OrderClient.GetExceptionSummary(c, &__.GetExceptionSummaryReq{
		StartDate: req.StartDate,
		EndDate:   req.EndDate,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询异常摘要行为
	middleware.RecordClickBehavior(c, userId, "查询异常摘要", map[string]interface{}{
		"startDate": req.StartDate,
		"endDate":   req.EndDate,
		"userId":    req.UserId,
		"success":   err == nil,
	})

	response.Success(c, "查询异常摘要成功", res)
}

// AutoDetectAndFix
// @Summary      自动检测和修复
// @Description  自动检测和修复异常
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        fix   body    request.AutoDetectAndFixReq    true  "自动检测和修复参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/exception/auto-fix [post]
// @Security TokenAuth
func AutoDetectAndFix(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.AutoDetectAndFixReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以执行自动修复
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以执行自动修复")
		return
	}

	// 调用自动检测和修复服务
	res, err := config.OrderClient.AutoDetectAndFix(c, &__.AutoDetectAndFixReq{})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录自动检测和修复行为
	middleware.RecordClickBehavior(c, userId, "自动检测和修复", map[string]interface{}{
		"startDate": req.StartDate,
		"endDate":   req.EndDate,
		"fixType":   req.FixType,
		"userId":    req.UserId,
		"success":   err == nil,
	})

	response.Success(c, "自动检测和修复完成", res)
}

// ManualProcess
// @Summary      人工处理
// @Description  人工处理异常
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        process   body    request.ManualProcessReq    true  "人工处理参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/exception/manual-process [post]
// @Security TokenAuth
func ManualProcess(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.ManualProcessReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以执行人工处理
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以执行人工处理")
		return
	}

	// 调用人工处理服务
	res, err := config.OrderClient.ManualProcess(c, &__.ManualProcessReq{
		AbnormalId:    req.Action,
		ProcessResult: req.ProcessResult,
		ProcessedBy:   uint32(userId),
		Action:        strconv.Itoa(int(req.Action)),
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录人工处理行为
	middleware.RecordClickBehavior(c, userId, "人工处理", map[string]interface{}{
		"action":  req.Action,
		"success": err == nil,
	})

	response.Success(c, "人工处理完成", res)
}

// DisputeResolution
// @Summary      争议解决
// @Description  争议解决
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        resolution   body    request.DisputeResolutionReq    true  "争议解决参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/dispute/resolution [post]
// @Security TokenAuth
func DisputeResolution(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.DisputeResolutionReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以解决争议
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以解决争议")
		return
	}

	// 调用争议解决服务
	res, err := config.OrderClient.DisputeResolution(c, &__.DisputeResolutionReq{
		DisputeId:  req.DisputeId,
		Resolution: req.Resolution,
		ResolvedBy: uint32(userId),
		Action:     req.Reason,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录争议解决行为
	middleware.RecordClickBehavior(c, userId, "争议解决", map[string]interface{}{
		"disputeId": req.DisputeId,
		"reason":    req.Reason,
		"success":   err == nil,
	})

	response.Success(c, "争议解决完成", res)
}

// GetTransactionDetails
// @Summary      获取交易详情列表
// @Description  获取交易详情列表
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        transaction   query    request.FinancialReconciliationReq    true  "交易详情参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/transaction/details [get]
// @Security TokenAuth
func GetTransactionDetails(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.FinancialReconciliationReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以查看所有数据
	if authorityId != 3 && req.UserId == "" {
		response.ParameterError(c, "权限不足", "非管理员用户必须指定用户ID")
		return
	}

	// 调用获取交易详情服务
	res, err := config.OrderClient.GetTransactionDetails(c, &__.FinancialReconciliationReq{
		StartDate:       req.StartDate,
		EndDate:         req.EndDate,
		OrderStatus:     req.OrderStatus,
		PaymentMethod:   req.PaymentMethod,
		Page:            req.Page,
		PageSize:        req.PageSize,
		TransactionType: req.TransactionType,
		UserId:          req.UserId,
		DriverId:        req.DriverId,
		MinAmount:       req.MinAmount,
		MaxAmount:       req.MaxAmount,
		OrderSn:         req.OrderSn,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询交易详情行为
	middleware.RecordClickBehavior(c, userId, "查询交易详情", map[string]interface{}{
		"startDate":     req.StartDate,
		"endDate":       req.EndDate,
		"orderStatus":   req.OrderStatus,
		"paymentMethod": req.PaymentMethod,
		"page":          req.Page,
		"pageSize":      req.PageSize,
		"userId":        req.UserId,
		"success":       err == nil,
	})

	response.Success(c, "查询交易详情成功", res)
}

// GetTransactionDetailById
// @Summary      获取单条交易详情
// @Description  获取单条交易详情
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        transaction   query    request.TransactionDetailByIdReq    true  "交易详情参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/transaction/detail [get]
// @Security TokenAuth
func GetTransactionDetailById(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.TransactionDetailByIdReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用获取单条交易详情服务
	res, err := config.OrderClient.GetTransactionDetailById(c, &__.TransactionDetailByIdReq{
		Id: req.Id,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询单条交易详情行为
	middleware.RecordClickBehavior(c, userId, "查询单条交易详情", map[string]interface{}{
		"id":      req.Id,
		"success": err == nil,
	})

	response.Success(c, "查询单条交易详情成功", res)
}

// GenerateBilling
// @Summary      生成账单
// @Description  生成账单
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        billing   body    request.GenerateBillingReq    true  "生成账单参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/billing/generate [post]
// @Security TokenAuth
func GenerateBilling(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.GenerateBillingReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用生成账单服务
	res, err := config.OrderClient.GenerateBilling(c, &__.GenerateBillingReq{
		UserId:   req.UserId,
		UserType: req.UserType,
		BillType: req.BillType,
		Period:   req.Period,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录生成账单行为
	middleware.RecordClickBehavior(c, userId, "生成账单", map[string]interface{}{
		"userId":   req.UserId,
		"userType": req.UserType,
		"billType": req.BillType,
		"period":   req.Period,
		"success":  err == nil,
	})

	response.Success(c, "生成账单成功", res)
}

// GetBillingList
// @Summary      获取账单列表
// @Description  获取账单列表
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        billing   query    request.GetBillingListReq    true  "获取账单列表参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/billing/list [get]
// @Security TokenAuth
func GetBillingList(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.GetBillingListReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用获取账单列表服务
	res, err := config.OrderClient.GetBillingList(c, &__.GetBillingListReq{
		UserId:   req.UserId,
		UserType: req.UserType,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询账单列表行为
	middleware.RecordClickBehavior(c, userId, "查询账单列表", map[string]interface{}{
		"userId":   req.UserId,
		"userType": req.UserType,
		"page":     req.Page,
		"pageSize": req.PageSize,
		"success":  err == nil,
	})

	response.Success(c, "查询账单列表成功", res)
}

// GetBillingDetails
// @Summary      获取账单明细
// @Description  获取账单明细
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        billing   query    request.GetBillingDetailsReq    true  "获取账单明细参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/billing/details [get]
// @Security TokenAuth
func GetBillingDetails(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.GetBillingDetailsReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用获取账单明细服务
	res, err := config.OrderClient.GetBillingDetails(c, &__.GetBillingDetailsReq{
		BillingId: req.BillingId,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询账单明细行为
	middleware.RecordClickBehavior(c, userId, "查询账单明细", map[string]interface{}{
		"billingId": req.BillingId,
		"success":   err == nil,
	})

	response.Success(c, "查询账单明细成功", res)
}

// ConfirmBilling
// @Summary      确认账单
// @Description  确认账单
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        billing   body    request.ConfirmBillingReq    true  "确认账单参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/billing/confirm [post]
// @Security TokenAuth
func ConfirmBilling(c *gin.Context) {
	userId := c.GetUint("userId")

	var req request.ConfirmBillingReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 调用确认账单服务
	res, err := config.OrderClient.ConfirmBilling(c, &__.ConfirmBillingReq{
		BillingId: req.BillingId,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录确认账单行为
	middleware.RecordClickBehavior(c, userId, "确认账单", map[string]interface{}{
		"billingId": req.BillingId,
		"success":   err == nil,
	})

	response.Success(c, "确认账单成功", res)
}

// DetectAbnormalTransactions
// @Summary      检测异常交易
// @Description  检测异常交易
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/abnormal/detect [post]
// @Security TokenAuth
func DetectAbnormalTransactions(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	// 权限检查：只有管理员可以检测异常交易
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以检测异常交易")
		return
	}

	// 调用检测异常交易服务
	res, err := config.OrderClient.DetectAbnormalTransactions(c, &__.DetectAbnormalTransactionsReq{})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录检测异常交易行为
	middleware.RecordClickBehavior(c, userId, "检测异常交易", map[string]interface{}{
		"success": err == nil,
	})

	response.Success(c, "检测异常交易完成", res)
}

// GetAbnormalTransactions
// @Summary      获取异常交易列表
// @Description  获取异常交易列表
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        abnormal   query    request.GetAbnormalTransactionsReq    true  "获取异常交易列表参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/abnormal/list [get]
// @Security TokenAuth
func GetAbnormalTransactions(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.GetAbnormalTransactionsReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以查看异常交易
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以查看异常交易")
		return
	}

	// 调用获取异常交易列表服务
	res, err := config.OrderClient.GetAbnormalTransactions(c, &__.GetAbnormalTransactionsReq{
		Status:   req.Status,
		Page:     req.Page,
		PageSize: req.PageSize,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录查询异常交易列表行为
	middleware.RecordClickBehavior(c, userId, "查询异常交易列表", map[string]interface{}{
		"status":   req.Status,
		"page":     req.Page,
		"pageSize": req.PageSize,
		"success":  err == nil,
	})

	response.Success(c, "查询异常交易列表成功", res)
}

// ProcessAbnormalTransaction
// @Summary      处理异常交易
// @Description  处理异常交易
// @Tags         财务对账模块
// @Accept       json
// @Produce      json
// @Param        abnormal   body    request.ProcessAbnormalTransactionReq    true  "处理异常交易参数"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /financial/abnormal/process [post]
// @Security TokenAuth
func ProcessAbnormalTransaction(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")

	var req request.ProcessAbnormalTransactionReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}

	// 权限检查：只有管理员可以处理异常交易
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以处理异常交易")
		return
	}

	// 调用处理异常交易服务
	res, err := config.OrderClient.ProcessAbnormalTransaction(c, &__.ProcessAbnormalTransactionReq{
		AbnormalId:    req.AbnormalId,
		ProcessResult: req.ProcessResult,
		ProcessedBy:   uint32(userId),
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}

	// 记录处理异常交易行为
	middleware.RecordClickBehavior(c, userId, "处理异常交易", map[string]interface{}{
		"abnormalId":    req.AbnormalId,
		"processResult": req.ProcessResult,
		"success":       err == nil,
	})

	response.Success(c, "处理异常交易完成", res)
}

// 获取导出进度
func GetExportProgress(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以获取导出进度")
		return
	}
	var req request.GetExportProgress
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}
	res, err := config.OrderClient.GetExportProgress(c, &__.ExportProgressReq{
		TaskId: req.TaskId,
		UserId: uint32(userId),
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}
	response.Success(c, "获取导出进度成功", res)
}

// 获取导出任务状态
func GetExportTaskFinancialStatus(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以获取导出任务状态")
		return
	}
	var req request.GetExportTaskFinancialStatus
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}
	res, err := config.OrderClient.GetExportTaskFinancialStatus(c, &__.GetExportTaskFinancialStatusReq{
		TaskId: req.TaskId,
		UserId: uint32(userId),
	})
	if err != nil {
		response.SrvError(c, "服务器错误", err.Error())
		return
	}
	response.Success(c, "获取导出任务状态成功", res)

}

// 获取导出任务列表
func GetExportTaskList(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以获取导出任务列表")
		return
	}
	var req request.ExportTaskListReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}
	res, err := config.OrderClient.GetExportTaskList(c, &__.ExportTaskListReq{
		UserId:    uint32(userId),
		Page:      req.Page,
		PageSize:  req.PageSize,
		Status:    req.Status,
		StartDate: req.StartDate,
		EndDate:   req.EndDate,
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}
	response.Success(c, "获取导出任务列表成功", res)
}

// 删除导出任务
func DeleteExportTask(c *gin.Context) {
	userId := c.GetUint("userId")
	authorityId := c.GetUint("authorityId")
	if authorityId != 3 {
		response.ParameterError(c, "权限不足", "只有管理员可以删除导出任务")
		return
	}
	var req request.DeleteExportTaskReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数错误", err.Error())
		return
	}
	res, err := config.OrderClient.DeleteExportTask(c, &__.DeleteExportTaskReq{
		TaskId: req.TaskId,
		UserId: uint32(userId),
	})
	if err != nil {
		response.SrvError(c, "服务端错误", err.Error())
		return
	}
	response.Success(c, "删除导出任务成功", res)
}
